import os
import shutil
import time
from datetime import  datetime
import configparser
import argparse
DEFAULT_CONFIG_FILENAME = './S50.ini'
DEFAULT_INPUT_FOLDER = './input'
DEFAULT_OUTPUT_FOLDER = './output'
DEFAULT_WAIT_TIME = 60
def get_time_by_filename(filename = ""):
    try:
        output_time = int( str(filename)[-15-4:-4].replace('-', ''))
        # print(output_time)
    except:
        print(f'Error: cannot convert TIME from S50 filename{output_time}')
        return 0
    return output_time
def find_latest_fit_file(input_folder):
    latest_file = None
    latest_date = ""
    latest_time = 0
    list_fitsfile_shortname =[]
    for file in os.listdir(input_folder):
        if file.endswith('.fit'):
            if file not in list_fitsfile_shortname:
                list_fitsfile_shortname.append(file)
    # print(list_fitsfile_shortname)
    for i in list_fitsfile_shortname:
                # file_path = os.path.join(root, file)
                # last_modified_time = os.path.getmtime(file_path)
                # print(i)
                last_modified_time = get_time_by_filename(filename = str(i))
                # print(last_modified_time)
                if last_modified_time > latest_time:
                    latest_time = last_modified_time
                    latest_file = i

    latest_date = str(latest_time)[:8]
    print(latest_file,latest_date)
    return os.path.join(input_folder,latest_file),latest_date
def monitor_folders(input_folder, output_folder, wait_time=60):
    # 创建输出文件夹，如果它不存在
    os.makedirs(output_folder, exist_ok=True)
    latest_data_str='latest file\'s date'
    new_sub_folder=""
    new_file_name=""
    monitor_counter = 1
    while True:
        print(f'--{monitor_counter}---{datetime.now()}---')
        try:
            latest_file,latest_data_str = find_latest_fit_file(input_folder)
            new_sub_folder = os.path.join(output_folder,latest_data_str)
            os.makedirs(new_sub_folder, exist_ok=True)
            if latest_file:
                new_file_name =f"T_CrB_{os.path.basename(latest_file)}"
                output_filename = os.path.join(new_sub_folder,new_file_name)

                if not os.path.exists(output_filename):
                    print(f'Coping file:: {latest_file} to {output_filename}')
                    try:
                        shutil.copy2(latest_file, output_filename)
                    except Exception as ex:
                        print(f"ERROR: when copying:{ex}")
                else:
                    print("INFO:output file Existed!!")
            else:
                print(f"No fit file found in{input_folder}")
        except Exception as ex:
            print(f"ERROR: monitering error:{ex}")
            pass  # 忽略监控过程中的错误

        print(f"INFO:complete. waiting for {wait_time}")
        time.sleep(int(wait_time))  # 每隔1分钟检查一次
        monitor_counter += 1

def get_configuration(config_filename=''):
    global  DEFAULT_CONFIG_FILENAME,DEFAULT_INPUT_FOLDER,DEFAULT_OUTPUT_FOLDER
    config = configparser.ConfigParser()
    if config_filename != '':
        print(f'INFO:Not specify config file, using DEFAULT config file:{DEFAULT_CONFIG_FILENAME}')
        try :
            config.read( DEFAULT_CONFIG_FILENAME )
        except:
            print(f'ERROR C1:DEFAULT config file:{DEFAULT_CONFIG_FILENAME} NOT found,using default input/output path')
            return DEFAULT_INPUT_FOLDER,DEFAULT_OUTPUT_FOLDER

    # 检查配置文件中是否有目录配置
    if not config.has_section('directories'):
        print(f'ERROR: No input/output path found in {config_filename},using default input/output path')
        return DEFAULT_INPUT_FOLDER, DEFAULT_OUTPUT_FOLDER

    input_folder = config.get('directories', 'input_folder', fallback=DEFAULT_INPUT_FOLDER)
    output_folder = config.get('directories', 'output_folder', fallback=DEFAULT_OUTPUT_FOLDER)
    wait_time = config.get('common', 'wait_time', fallback=DEFAULT_WAIT_TIME)
    return input_folder, output_folder,wait_time


def parse_arguments():
    parser = argparse.ArgumentParser(description='监听输入文件夹并复制新的 .fit 文件。')
    parser.add_argument('--config', type=str, help='config file')
    parser.add_argument('--input', type=str, help='input S50 fits path')
    parser.add_argument('--output', type=str, help='output path')
    parser.add_argument('--waittime', type=int, help='wait time(seconds)')
    return parser.parse_args()
def main():
    args = parse_arguments()
    config_filename = args.config
    input_folder = args.input
    output_folder = args.output
    wait_time = args.waittime
    if not config_filename:
        if os.path.exists(DEFAULT_CONFIG_FILENAME):
            config_filename = DEFAULT_CONFIG_FILENAME
    # 如果命令行参数没有提供，尝试从配置文件读取
    if not wait_time:
        print("INFO:Not specify waittime")
        if config_filename:
            _, _ ,wait_time= get_configuration(config_filename=config_filename)
        elif os.path.exists(DEFAULT_CONFIG_FILENAME):
            _, _,wait_time = get_configuration(config_filename=DEFAULT_CONFIG_FILENAME)
        else:
            _, _ = DEFAULT_INPUT_FOLDER, DEFAULT_OUTPUT_FOLDER
    if not input_folder:
        print("INFO:Not specify input path")
        if config_filename:
            input_folder, _, _= get_configuration(config_filename=config_filename)
        elif os.path.exists(DEFAULT_CONFIG_FILENAME):
            input_folder, _, _= get_configuration(config_filename=DEFAULT_CONFIG_FILENAME)
        else:
            input_folder, _ = DEFAULT_INPUT_FOLDER, DEFAULT_OUTPUT_FOLDER
    if not output_folder:
        print("INFO:Not specify output path")
        if config_filename:
            _, output_folder,_ = get_configuration(config_filename=config_filename)
        elif os.path.exists(DEFAULT_CONFIG_FILENAME):
            _, output_folder,_ = get_configuration(config_filename=DEFAULT_CONFIG_FILENAME)
        else:
            _, output_folder = DEFAULT_INPUT_FOLDER, DEFAULT_OUTPUT_FOLDER

    print(f"input:{input_folder}--->ouput:{output_folder}")
    if os.path.exists(input_folder):
        # 启动文件监控
        monitor_folders(input_folder, output_folder,wait_time)
    else:
        print("Please specify a valid input path, exit now")



if __name__ == "__main__":
    main()

